/* Copyright 2003, 2008 Gregor Hohpe (http://www.eaipatterns.com) */

using System;
using System.Messaging;
using System.Xml;

using MessageGateway;

namespace MessageGatewayMSMQ
{
    /* Realizes the IMessageSender and IMessageReceiver interfaces on top
     * of good old MSMQ.
     */
    public class MessageReceiverMSMQ : IMessageReceiver
    {
        protected MessageQueue queue;
        protected OnMsgEvent receiver;

        public MessageReceiverMSMQ(MessageQueue queue)
        {
            this.queue = queue;
            this.queue.Formatter = new ActiveXMessageFormatter();
            receiver = new OnMsgEvent(NullEvent);
        }

        public void AddEventHandler(OnMsgEvent handler)
        {
            receiver += handler;
        }

        public void Activate()
        {
            try
            {
                queue.ReceiveCompleted += new ReceiveCompletedEventHandler(OnReceiveCompleted);
                queue.BeginReceive();
            }
            catch (MessageQueueException e)
            {
                throw new ApplicationException("Could not connect to messaging system. Make sure the MSMQ service is running.", e);
            }
		}
		
        private void NullEvent(XmlDocument msg){}

		private void OnReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
		{
			MessageQueue mq = (MessageQueue)source;
			Message msg = mq.EndReceive(asyncResult.AsyncResult);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml((string)msg.Body);
             
			receiver(doc);
			mq.BeginReceive(); 
		}	

    }

	public class MessageSenderMSMQ : IMessageSender
	{
        protected MessageQueue queue;

		public MessageSenderMSMQ(MessageQueue queue)
		{
            this.queue = queue;
            this.queue.Formatter = new ActiveXMessageFormatter();
        }


        public void Send(XmlDocument msg)
        {
            try
            {
                queue.Send(msg.OuterXml);
            }
            catch (MessageQueueException e)
            {
                throw new ApplicationException("Could not connect to messaging system. Make sure the MSMQ service is running.", e);
            }
        }

    }


}
